package cn.itcast.sms.action;

import cn.itcast.crm.domain.Customer;
import cn.itcast.sms.utils.BaseAction;
import cn.itcast.sms.utils.SmsUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;
import sun.awt.ModalExclude;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;

/**
 * Created by Administrator on 2017/7/27.
 */
@Controller
@Namespace("/")
@ParentPackage("json-default")
@Scope("protoType")
public class SendMessageAction extends BaseAction<Customer> {
    //注入jmsTemplate使用activeMq生产一条消息
    @Autowired
    @Qualifier("jmsQueueTemplate")
    private JmsTemplate jmsTemplate;
    @Action(value = "customer_SendSms")
    public String SendMessage() {
        //手机号码存到了customer对象中
        //生成一个六位的验证码
        String checkCode = RandomStringUtils.randomNumeric(6);
        System.out.println("验证码为:" + checkCode);
        //将验证码保存到session中
        ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), checkCode);
        //调用接口发送短信
        //编辑短信内容
        final String msg = checkCode;
        //调用ActiveMQ发送一个队列
        jmsTemplate.send("bos_sendMessage", new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                //发送一个队列,为map类型,key是电话号码,velue是发送的内容
                MapMessage mapMessage = session.createMapMessage();
                mapMessage.setString("telephone", model.getTelephone());
                mapMessage.setString("msg", msg);
                return mapMessage;
            }
        });
        return NONE;
    }
}
